<?php

declare (strict_types=1);

namespace app\api\model;

use app\api\service\User as UserService;
use app\common\model\Exchange as ExchangeModel;
use app\common\model\ExchangeCode;
use app\common\model\ExchangeLog;

/**
 * 物流公司模型
 * Class Express
 * @package app\api\model
 */
class Exchange extends ExchangeModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [

    ];

    public function echange($data){
        $code = $data['code'];
        if(!$code){
            return false;
        }
        $codeModel = new ExchangeCode();
        $code = $codeModel->where('code',$code)->where('store_id',self::$storeId)->find();

        $logModel = new ExchangeLog();
        $log = $logModel->where('code_id',$code->id)->find();
        if($log){
            return false;
        }
        if(!$code || $code->status === 0){
            return false;
        }
        $logModel->startTrans();
        try {
            $data['user_id'] = UserService::getCurrentLoginUserId();
            $data['code_id'] = $code->id;
            $data['status'] = 0;
            $data['createtime'] = time();
            $data['store_id'] = self::$storeId;
            $exchangeModel = new \app\common\model\Exchange();
            $exchange = $exchangeModel->where('id',$code->exchange_id)->find();
            if($exchange->money > 0){
                $userModel = new \app\common\model\User();
                $user = $userModel->get($data['user_id']);
                $user->balance += doubleval($exchange->money);
                $user->save();
            }
            $res = ExchangeLog::create($data);
            $codeModel->where('code',$code->code)->update(['status'=>0]);
            if($res){
                $logModel->commit();
                return true;
            }else{
                $logModel->rollback();
                return false;
            }
        }catch (\Exception $exception){
            $logModel->rollback();
            return false;
        }
    }
}